package com.ujiuye.web;

import com.ujiuye.enity.Student;
import com.ujiuye.service.StuService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.UUID;

@MultipartConfig
@WebServlet("/addStu")
public class AddServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter pw = resp.getWriter();
        //获取上传的图片名字
        Part p = req.getPart("spic");
        String fileName = p.getSubmittedFileName();
        //重命名图片
        fileName = UUID.randomUUID() + fileName;
        //设置上传路径
        String path = "D:/qqqq";
        Student s = new Student();
        //获取表单数据,映射到 学生对象s中
        Map<String, String[]> map = req.getParameterMap();
        try {
            BeanUtils.populate(s, map);
            StuService ss = new StuService();
            //在添加之前给spic属性赋值
            s.setSpic(fileName);
            boolean b = ss.addStu(s);
            if (b) {
                //总体过程:  添加成功-->显示学生信息 -->上传图片
                File f = new File(path);
                //如果路径不存在就创建路径
                if (!f.exists()) {
                    f.mkdirs();
                }
                //上传图片
                p.write(path + File.separator + fileName);
                req.getRequestDispatcher("/show").forward(req, resp);
            } else {
                pw.println("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
